package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {

	private static BaseDao instance;
	private final String DB_URL = "jdbc:mysql://localhost:3306/gallery_db";
	private final String USERNAME = "root";
	private final String PASSWORD = "";
	private Connection conn = null;
	
	
	protected BaseDao() {
		
	}
	
	public static BaseDao getInstance() {
		if(instance == null) {
			instance = new BaseDao();
		}
		return instance;
	}
	
	public Connection getConnection() throws Exception{
		if(conn == null || conn.isClosed()) {
			Class.forName("com.mysql.jdbc.Driver");
			this.conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
		}
		return this.conn;
	}
	
	public ResultSet executeQuery(String query) throws Exception{
		Statement statement = getConnection().createStatement();
		return statement.executeQuery(query);
	}
	
	public int executeUpdate(String query) throws Exception {
		Statement statement = getConnection().createStatement();
		return statement.executeUpdate(query); 
	}
	
	public int executeUpdate(String query, int autoGenarateKey ) throws Exception {
		Statement statement = getConnection().createStatement();
		return statement.executeUpdate(query, autoGenarateKey); 
	}
	
	public static void main(String[] args) {
		BaseDao b = new BaseDao();
		try {
			b.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
